from django.views import View

from Account.models import Account
from User.models import User
from Venue.models import Venue
from sportsground.utils import Req
from sportsground.utils.Res import Res


class RegisterView(View):
    """ 注册 """

    @Req.getJson
    def post(self, request):
        username = request.json_dict.get("username")
        password = request.json_dict.get("password")
        role = request.json_dict.get("role")

        if role not in Account.Roles.list():
            return Res.Json(Res.ParamErr)

        account = Account.objects.filter(username=username, role=role).first()
        if account:
            return Res.Json(Res.Warn, msg="该用户已注册")

        account = Account(username=username, role=role)
        account.set_password(password)
        # 分配对应角色
        if role == Account.Roles.User:
            account.user = User.create()
        elif role == Account.Roles.Venue:
            account.venue = Venue.create()
        account.save()
        return Res.Json(Res.OK)
